"""
__author__='fanxn19000'
__date__='2018/09/25'
"""
from django.shortcuts import HttpResponse
from .models import User
from Util.token import TokenUtil
import json

from apscheduler.schedulers.background import BackgroundScheduler
from django_apscheduler.jobstores import DjangoJobStore, register_events, register_job
# 定时任务间隔时间
# scheduleSecond = 60

token = TokenUtil()

def login(request):
    body_unicode = request.body.decode()  # getting payload data into json
    body = json.loads(body_unicode)  # converting json into array

    realm_account = body["realm_account"]
    password = body['password']
    login = User.objects.filter(realm_account=realm_account).filter(password=password)
    response = {}
    if login:
        user_token = token.getToken(realm_account)
        response = {'user_token': user_token,
                    'error_no': "0",
                    'error_info': "登录成功！"}
    else:
        response = {'error_no': "-1", 'error_info': "用户名或者密码错误！",'user_token':""}

    return HttpResponse(json.dumps(response), content_type="application/json")

def userQuery(request):
    body_unicode = request.body.decode()  # getting payload data into json
    body = json.loads(body_unicode)
    user_token = body["user_token"]
    if token.isLogin(user_token):
        realm_account = token.getRealmAccount(user_token)
        resultList = list(User.objects.filter(realm_account=realm_account).all().values())
        response = {}
        response = {'error_no': "0", 'error_info': "", 'resultList': resultList}
    else:
        response = {'error_no': "-1", 'error_info': "未登录，请登录系统！", 'resultList': []}
    return HttpResponse(json.dumps(response), content_type="application/json")

def userQueryAll(request):
    body_unicode = request.body.decode()  # getting payload data into json
    body = json.loads(body_unicode)
    user_token = body["user_token"]
    response = {}
    if token.isLogin(user_token):
        realm_account = token.getRealmAccount(user_token)
        name = body["name"]
        if name==None or len(name) == 0:
            resultList = list(User.objects.all().values())
        else:
            resultList = list(User.objects.filter(name=name).all().values())
        response = {'error_no': "0", 'error_info': "登录成功！", 'resultList': resultList}
    else:
        response = {'error_no': "-1", 'error_info': "未登录，请登录系统！", 'resultList': []}
    return HttpResponse(json.dumps(response), content_type="application/json")

def userCreate(request):
    body_unicode = request.body.decode()  # getting payload data into json
    body = json.loads(body_unicode)
    user_token = body["user_token"]
    response = {}
    if token.isLogin(user_token):
        resultQuery = list(User.objects.filter(realm_account=body["realm_account"]).all().values())
        if len(resultQuery) > 0 :
            response = {'error_no': "-1", 'error_info': "添加的用户已经存在！"}
        else:
            User.objects.create(name=body["name"],
                                password=body["password"],
                                empl_number=body["empl_number"],
                                realm_account=body["realm_account"],
                                department=body["department"],
                                test_group=body["test_group"],
                                email=body["email"])
            response = {'error_no': "0", 'error_info': "用户添加成功!"}

    else:
        response = {'error_no': "-1", 'error_info': "未登录，请登录系统！"}
    return HttpResponse(json.dumps(response), content_type="application/json")

def userUpdate(request):
    body_unicode = request.body.decode()  # getting payload data into json
    body = json.loads(body_unicode)
    user_token = body["user_token"]
    response = {}
    if token.isLogin(user_token):
        updateUser = User.objects.get(user_id=body['user_id'])
        updateUser.name = body['name']
        updateUser.password = body['password']
        updateUser.empl_number = body['empl_number']
        updateUser.realm_account = body['realm_account']
        updateUser.department = body['department']
        updateUser.test_group = body['test_group']
        updateUser.email = body['email']
        updateUser.save()
        response = {'error_no': "0", 'error_info': "用户修改成功!"}

    else:
        response = {'error_no': "-1", 'error_info': "未登录，请登录系统！"}
    return HttpResponse(json.dumps(response), content_type="application/json")

def userDelete(request):
    body_unicode = request.body.decode()  # getting payload data into json
    body = json.loads(body_unicode)
    user_token = body["user_token"]
    response = {}
    if token.isLogin(user_token):
        User.objects.get(user_id=body['user_id']).delete()
        response = {'error_no': "0", 'error_info': "删除用户成功"}
    else:
        response = {'error_no': "-1", 'error_info': "未登录，请登录系统！"}
    return HttpResponse(json.dumps(response), content_type="application/json")

def loginOut(request):
    body_unicode = request.body.decode()  # getting payload data into json
    body = json.loads(body_unicode)
    user_token = body["user_token"]
    response = {}
    if token.isLogin(user_token):
        token.tokenOut(user_token)
        response = {'error_no': "0", 'error_info': "用户退出登录!"}
    else:
        response = {'error_no': "0", 'error_info': "用户退出登录!"}
    return HttpResponse(json.dumps(response), content_type="application/json")

def qryAllDepartment(request):
    body_unicode = request.body.decode()  # getting payload data into json
    body = json.loads(body_unicode)
    user_token = body["user_token"]
    response = {}
    if token.isLogin(user_token):
        resultList=[]
        resultListTemp = list(User.objects.values('department').all())
        for result in resultListTemp:
            if not result in resultList:
                resultList.append(result)
        response = {'error_no': "0", 'error_info': "用户退出登录!","resultList":resultList}
    else:
        response = {'error_no': "-1", 'error_info': "未登录，请登录系统！"}
    return HttpResponse(json.dumps(response), content_type="application/json")

# 根据部门获取邮件地址
def qryEmailbyDepartment(depart):
    department = str(depart)
    email = ""
    if department.count(',') >0:
        departmentArr = department.split(',')
        for subDepart in departmentArr:
            resultList = list(User.objects.filter(department=subDepart).values('email').all())
            if len(resultList) > 0:
                for subList in resultList:
                    email = email + ";" + subList['email']
    else:
        resultList = list(User.objects.filter(department=department).values('email').all())
        if len(resultList) > 0:
            for subList in resultList:
                email = email + ";" + subList['email']
    if len(email) > 1:
        return email[1:]
    else:
        return email
# 定时任务
# try:
#     scheduler = BackgroundScheduler()
#     scheduler.add_jobstore(DjangoJobStore(), "default")
#
#
#     def test_job():
#         print("666666")
#
#
#     scheduler.add_job(test_job, 'interval', seconds=scheduleSecond)
#
#     register_events(scheduler)
#     scheduler.start()
#
# except Exception as e:
#     print(e)
#     scheduler.shutdown()